package com.gin.no_gay_alliance.fragment.daily;

import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;

import androidx.annotation.NonNull;

import com.gin.common.utils.StrUtils;
import com.gin.jackson.utils.ObjectUtils;
import com.gin.nga.exception.NgaClientException;
import com.gin.nga.exception.NgaException;
import com.gin.no_gay_alliance.adpter.MissionAdapter;
import com.gin.no_gay_alliance.app.MyApplication;
import com.gin.no_gay_alliance.callback.Callback;
import com.gin.no_gay_alliance.databinding.FragmentDailyMissionBinding;
import com.gin.no_gay_alliance.enums.MessageWhat;
import com.gin.no_gay_alliance.fragment.base.BaseBindingFragment;
import com.gin.no_gay_alliance.viewmodel.MissionModel;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 任务
 *
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/9/13 09:56
 **/
public class MissionFragment extends BaseBindingFragment<FragmentDailyMissionBinding> implements Callback<List<MissionModel>>, CompoundButton.OnCheckedChangeListener {
    private MissionAdapter adapter;

    /**
     * onCreateView 的后续操作
     */
    @Override
    protected void onCreateView() {
        Log.d(TAG, "onCreateView: " + "任务");
        b.tvWarning.setVisibility(View.GONE);
        adapter = new MissionAdapter(requireContext());
        adapter.setHandler(handler);
        b.recyclerView.setAdapter(adapter);
        b.swipeRefreshLayout.setOnRefreshListener(this::refresh);
    }

    /**
     * 处理消息
     *
     * @param message 消息
     * @return 是否消耗
     */
    @Override
    public boolean handleMessage(@NonNull Message message) {
        // 签到成功后刷新任务列表
        if (message.what == MessageWhat.ON_SUCCESS_CHECK_IN_REQUEST.ordinal()) {
            refresh();
            return true;
        }

        return super.handleMessage(message);
    }

    @Override
    public void onResume() {
        super.onResume();
        sendRequest(false);
        b.swAutoCheckIn.setOnCheckedChangeListener(null);
        b.swAutoCheckIn.setChecked(MyApplication.app.managerFactory.getMissionManager().isAutoCheckIn());
        b.swAutoCheckIn.setOnCheckedChangeListener(this);
    }

    public void refresh() {
        sendRequest(true);
    }

    /**
     * 请求成功回调
     *
     * @param data 数据
     */
    @Override
    public void onSuccess(List<MissionModel> data) {
        ui(() -> {
            b.tvWarning.setVisibility(View.GONE);
            adapter.updateData(data);
        });
        onRequestFinally();
    }

    /**
     * 请求之前执行的操作
     */
    @Override
    public void beforeRequest() {
        ui(() -> b.swipeRefreshLayout.setRefreshing(true));
    }

    /**
     * 请求失败回调(一般为网络访问错误)
     *
     * @param call call
     * @param e    错误
     */
    @Override
    public void onFailure(@NonNull Call call, @NonNull IOException e) {
        Callback.super.onFailure(call, e);
        onRequestFinally();
        showWarn(e.getMessage());
    }

    /**
     * 处理Nga异常
     *
     * @param e 异常
     */
    @Override
    public void handleException(NgaException e) {
        Callback.super.handleException(e);
        onRequestFinally();
        if (e instanceof NgaClientException) {
            Map<Integer, String> reason = ((NgaClientException) e).getReason();
            String t0 = reason.get(0);
            String t1 = reason.get(1);

            if (!ObjectUtils.isEmpty(t0) && !StrUtils.isNumber(t0)) {
                showWarn(t0);
            } else if (!ObjectUtils.isEmpty(t1) && !StrUtils.isNumber(t1)) {
                showWarn(t1);
            }
        }
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (buttonView == b.swAutoCheckIn) {
            Log.d(TAG, "onCheckedChanged: " + isChecked);
            if (isChecked) {
                toast("自动签到将在APP启动时执行\n(无论当前的账号是哪个)");
                MyApplication.app.managerFactory.getMissionManager().addAutoCheckInUser();
            } else {
                MyApplication.app.managerFactory.getMissionManager().removeAutoCheckInUser();
            }
        }
    }

    /**
     * 请求结束
     */
    private void onRequestFinally() {
        ui(() -> b.swipeRefreshLayout.setRefreshing(false));
    }

    private void sendRequest(boolean ignoreCache) {
        MyApplication.app.managerFactory.getMissionManager().missionList(ignoreCache, this);
    }

    /**
     * 显示警告信息
     *
     * @param text
     */
    private void showWarn(String text) {
        ui(() -> {
            b.swipeRefreshLayout.setVisibility(View.GONE);
            b.tvWarning.setVisibility(View.VISIBLE);
            b.tvWarning.setText(text);
        });
    }
}
